package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.program.IProgramAsyncService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by karkarrotxu on 2015/12/25.
 */
public class AutoProgramBroadCastTrigger {
    private static Logger logger = LoggerFactory.getLogger(AutoProgramBroadCastTrigger.class);

    @Autowired
    private ProgramService programService;

    @Autowired
    private IProgramAsyncService programAsyncService;

    @Autowired
    private BroadcastControlService broadcastControlService;


    public void task() {
        Thread thread = Thread.currentThread();
        long costStart = System.currentTimeMillis();
        logger.info("[AutoProgramBroadCastTrigger][start][{}]", thread.getName());
        try {

            long current = System.currentTimeMillis();
            long minTime = DateTimeUtil.getZeroTime(current);
            long maxTime = minTime + 2 * DateTimeUtil.DAY_TIME;
            List<ProgramData> list = null;
            int maxCount = 4000;
            list = programService.findNoBroadcastPrograms(minTime, maxTime, 0, maxCount);
            logger.info("[size] list.size={}", list.size());
            if (list.size() == 0) {
                logger.info("[no program task interrupt]");
                return;
            }
            for (ProgramData programData : list) {
                broadcastControlService.fillProgramBroadcast(programData);
                programService.doSyncById(programData.getId());
            }
        } catch (Exception e) {
            logger.error("exception e", e);
        }
        logger.info("[AutoProgramBroadCastTrigger][end][{}][cost={}]", thread.getName(), System.currentTimeMillis() - costStart);
    }
}
